<template>
  <div v-show="active === flag" class="step-main">
    <div class="step-content">
      <!-- 后端实体设置表格 -->
      <v-card elevation="10">
        <v-card-title>后端实体设置</v-card-title>
        <v-card-text>
          <v-data-table :items="tableFormCurr" :headers="headers" item-key="id" :loading="loading" :items-per-page="-1"
            class="backend-table">
            <template #item.drag="{ item }">
              <v-btn icon="mdi-drag" size="small" variant="text" class="move-btn" />
            </template>

            <template #item.fieldName="{ item }">
              <v-text-field v-model="item.fieldName" disabled variant="outlined" density="compact" hide-details />
            </template>

            <template #item.fieldComments="{ item }">
              <v-text-field v-model="item.fieldComments" disabled maxlength="100" counter variant="outlined"
                density="compact" hide-details />
            </template>

            <template #item.javaType="{ item }">
              <v-select v-model="item.javaType" :items="getJavaTypeOptions(item.fieldType)"
                :disabled="item.disabled || item.showType === '2'" :rules="columnRules.javaType" variant="outlined"
                density="compact" hide-details="auto" clearable placeholder="请选择Java类型" />
            </template>

            <template #item.dictTypeCode="{ item }">
              <v-text-field v-model="item.dictTypeCode" :disabled="item.disabled || item.showType !== '2'"
                :rules="getDictCodeRules(item)" variant="outlined" density="compact" hide-details="auto"
                placeholder="字典类型编号" />
            </template>

            <template #item.validateType="{ item }">
              <v-select v-model="item.validateType" :items="dictCurr.validate_type || []" item-title="dictName"
                item-value="dictValue" :disabled="item.disabled" multiple clearable variant="outlined" density="compact"
                hide-details placeholder="验证类别" />
            </template>
          </v-data-table>
        </v-card-text>
      </v-card>
    </div>

    <!-- 步骤底部 -->
    <StepFooter ref="stepFooterRef" :flag="flag" :min-flag="minFlag" :max-flag="maxFlag" :info-data="{
      obj: this,
      baseForm: baseFormCurr,
      tableForm: tableFormCurr
    }" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import StepFooter from './footer/StepFooter.vue';
import { deepClone } from '@/utils/clone';
import { isCode, isNull } from '@/utils/validate';

interface Props {
  active: number;
  minFlag: number;
  maxFlag: number;
  baseForm: any;
  tableForm: any[];
  dict: any;
  baseDictData: any;
}

const props = withDefaults(defineProps<Props>(), {
  active: 1,
  minFlag: 1,
  maxFlag: 1,
  baseForm: () => ({}),
  tableForm: () => [],
  dict: () => ({}),
  baseDictData: () => ({ fieldList: [], JavaFieldMap: {} })
});

const emit = defineEmits(['inform-flag', 'inform-data', 'change-step', 'close', 'submit']);

// 表格头部定义
const headers = [
  { title: '拖动', key: 'drag', width: 80, sortable: false },
  { title: '字段名称', key: 'fieldName', width: 200 },
  { title: '字段描述', key: 'fieldComments', width: 240 },
  { title: 'Java类型', key: 'javaType', width: 130 },
  { title: '字典类型编号', key: 'dictTypeCode', width: 160 },
  { title: '验证类别', key: 'validateType', width: 280 }
];

// 响应式数据
const flag = ref(3);
const title = ref('后端实体设置');
const loading = ref(false);
const stepFooterRef = ref();

const dictCurr = ref<any>({});
const baseFormCurr = ref<any>({});
const tableFormCurr = ref<any[]>([]);
const selectRows = ref<any[]>([]);

// 校验规则
const columnRules = {
  javaType: [
    (v: string) => !!v || '请选择Java类型'
  ]
};

// 获取字典编号校验规则
function getDictCodeRules(item: any) {
  return [
    (v: string) => {
      // 如果同行是字典，那么字典编号就必须非空
      if (item.showType === '2') {
        if (isNull(v)) {
          return '请输入字典编号';
        }
        if (!isCode(v)) {
          return '编号只能为字母、数字或下划线';
        }
      }
      return true;
    }
  ];
}

// 获取Java类型选项
function getJavaTypeOptions(fieldType: string) {
  // 临时测试数据
  const testJavaFieldMap = {
    'varchar': 'String',
    'int': 'Integer',
    'bigint': 'Long',
    'decimal': 'BigDecimal',
    'datetime': 'Date',
    'date': 'Date',
    'text': 'String',
    'char': 'String',
    'tinyint': 'Integer',
    'smallint': 'Integer',
    'mediumint': 'Integer',
    'float': 'Float',
    'double': 'Double',
    'timestamp': 'Date',
    'time': 'Time',
    'year': 'Integer',
    'blob': 'byte[]',
    'longtext': 'String'
  };

  if (!fieldType) {
    return [];
  }

  // 优先使用真实数据
  if (props.baseDictData?.JavaFieldMap) {
    const javaTypes = props.baseDictData.JavaFieldMap[fieldType];

    if (javaTypes) {
      // 如果是数组，直接返回
      if (Array.isArray(javaTypes)) {
        return javaTypes.map((type: string) => ({ title: type, value: type }));
      }

      // 如果是字符串，转换为数组
      if (typeof javaTypes === 'string') {
        return [{ title: javaTypes, value: javaTypes }];
      }
    }
  }

  // 使用测试数据作为备用
  const testJavaType = testJavaFieldMap[fieldType as keyof typeof testJavaFieldMap];
  if (testJavaType) {
    return [{ title: testJavaType, value: testJavaType }];
  }

  return [];
}

// 行选中
function setSelectRows(val: any[]) {
  selectRows.value = val;
}

// 监听 props 变化
watch(() => props.baseForm, (newV) => {
  baseFormCurr.value = deepClone(newV);
}, { deep: true });

watch(() => props.tableForm, (newV) => {
  tableFormCurr.value = deepClone(newV);
}, { deep: true });

watch(() => props.dict, (newV) => {
  dictCurr.value = deepClone(newV);
}, { deep: true });

// 监听 baseDictData 变化
watch(() => props.baseDictData, (newV) => {
  // 数据更新时重新计算Java类型选项
  if (tableFormCurr.value.length > 0 && newV?.JavaFieldMap) {
    // 触发响应式更新
    tableFormCurr.value = [...tableFormCurr.value];
  }
}, { deep: true });

// 组件挂载时执行
onMounted(() => {
  // 告诉父节点自己的 flag 编号
  emit('inform-flag', flag.value, title.value);

  // 拷贝 props
  baseFormCurr.value = deepClone(props.baseForm);
  tableFormCurr.value = deepClone(props.tableForm);
  dictCurr.value = deepClone(props.dict);
});
</script>

<style lang="scss">
.step-main {
  .step-content {
    height: 540px;
    overflow-y: auto;
  }

  .backend-table {
    .v-data-table__tbody tr {
      &:hover {
        background-color: rgba(0, 0, 0, 0.04);
      }
    }
  }

  .move-btn {
    cursor: grab;

    &:active {
      cursor: grabbing;
    }
  }
}
</style>
